package com.shiwaixiangcun.customer.ui.activity

import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import butterknife.ButterKnife
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.app.App
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.tencent.smtt.sdk.*
import kotlinx.android.synthetic.main.activity_privacy.*
import kotlinx.android.synthetic.main.top_bar_white.*
import java.util.*

/**
 * 隐私政策页面
 *
 * @author Administrator
 */
class PrivacyActivity : BaseActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_privacy)
        ButterKnife.bind(this)
        initViewAndEvent()
    }


    private fun initViewAndEvent() {
        tv_page_name.text = "隐私政策"
        back_left.setOnClickListener { finish() }
        removeCookie(this)
        webView.clearCache(true)
        webView.webChromeClient = MyWebChromeViewClient()
        webView.webViewClient = MyWebViewClient()
        val siteId = AppSharePreferenceMgr.get(App.getContext(), ConfigSps.CURRENT_SITE_ID, 20) as Int
        val header = HashMap<String, String>(2)

        header["siteId"] = "" + siteId
        webView.loadUrl(GlobalApi.getPrivacy, header)

    }

    /**
     * 清除Cookie
     *
     * @param context
     */
    private fun removeCookie(context: Context) {
        CookieSyncManager.createInstance(context)
        val cookieManager = CookieManager.getInstance()
        cookieManager.removeAllCookie()
        CookieSyncManager.getInstance().sync()
    }




    override fun onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            webView.clearHistory()

            (webView.parent as ViewGroup).removeView(webView)
            webView.destroy()
        }
        super.onDestroy()
    }

    private inner class MyWebChromeViewClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView, newProgress: Int) {
            if (newProgress == 100) {
                progress_bar.visibility = View.GONE
            } else {
                if (View.INVISIBLE == progress_bar.visibility) {
                    progress_bar.visibility = View.VISIBLE
                }
                progress_bar.progress = newProgress
            }
            super.onProgressChanged(view, newProgress)
        }


    }

    /**
     * 处理通知 ，请求事件
     */
    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }
    }
}
